<?php

namespace app\api\controller;

use app\common\logic\Data;
use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;
use Yurun\Util\HttpRequest;

class Push extends Base
{
  /**
   * 推送服务器列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function server_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('push_server_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('push_server_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      if ($vo['type'] == 'alert') {
        $vo['platform_title'] = self::getPlatform($vo['platform_alert']);
      } else {
        $vo['platform_title'] = self::getPlatform($vo['platform']);
      }
      $vo['type_title'] = self::getType($vo['type']);
      $vo['hook_key'] = (isset($vo['hook_key'])) ? 'https://21ds.cn/push/webhook?token=' . $vo['hook_key'] : '';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_server_list()
  {

    $dataList = Db::connect('mongodb')->name('push_server_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    return Result::Success($dataList);
  }
  public function all_tpl_list()
  {
    $dataList = Db::connect('mongodb')->name('push_tpl_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    return Result::Success($dataList);
  }
  public function tpl_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'cate_id' => input('param.cate_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id|aliyun_tpl_code|tencent_tpl_code', 'like', $data['title']];
    }
    if (!empty($data['cate_id'])) {
      $where[] = ['cate_id', '=', $data['cate_id']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('push_tpl_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('push_tpl_list')->where($where)->count('id');

    $cateList = Db::connect('mongodb')->name('push_tpl_cate')->field('_id,title')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['cate_title'] = isset($cateListArr[$vo['cate_id']]) ? $cateListArr[$vo['cate_id']] : '';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function tpl_cate_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('push_tpl_cate')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('push_tpl_cate')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_cate_list()
  {
    $selectResult = Db::connect('mongodb')->name('push_tpl_cate')->field('_id,title,pid,sort')->order('sort', 'desc')->select()->toArray();
    $sdata = new Data();
    foreach ($selectResult as &$vo) {
      $vo['title'] = $vo['title'];
      $vo['ids'] = join(',', $sdata->getArrSubIds($selectResult, $vo['_id'], '_id'));
    }
    $selectResult = $sdata->arr2table($selectResult, '_id');
    return Result::Success($selectResult);
  }
  public function send_log_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
      'send_time_ranges|发送时间'  => 'require',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'ps_id' => input('param.ps_id', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|cid|content|_id', 'like', $data['title']];
    }
    if (!empty($data['ps_id'])) {
      $where[] = ['ps_id', '=', $data['ps_id']];
    }
    $start_time = strtotime($data['send_time_ranges'][0]);
    $end_time = strtotime($data['send_time_ranges'][1]);
    if ($end_time - $start_time > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('send_push_log')->field('*')->where($where)->whereBetweenTime('send_time', $start_time, $end_time)->order('send_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('send_push_log')->where($where)->whereBetweenTime('send_time', $start_time, $end_time)->count('_id');

    $cateList = Db::connect('mongodb')->name('push_tpl_list')->field('_id,title')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }
    $serverList = Db::connect('mongodb')->name('push_server_list')->field('_id,title')->select()->toArray();
    $serverListArr = [];
    foreach ($serverList as &$vo) {
      $serverListArr[$vo['_id']] = $vo['title'];
    }

    foreach ($dataList as &$vo) {
      $vo['send_time'] = date('Y-m-d H:i:s', $vo['send_time']);
      // $vo['st_title'] = isset($cateListArr[$vo['pt_id']]) ? $cateListArr[$vo['pt_id']] : '';
      $vo['ps_title'] = isset($serverListArr[$vo['ps_id']]) ? $serverListArr[$vo['ps_id']] : '未知或已删除';
      $vo['read_time'] = (isset($vo['read_time']) && $vo['read_time'] > 0) ? date('Y-m-d H:i:s', $vo['read_time']) : '';
      $vo['cid'] = substr($vo['cid'], 0, 3) . '***' . substr($vo['cid'], -4);
      $vo['platform_title'] = self::getPlatform($vo['platform']);
      $vo['type_title'] = self::getType($vo['type']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function send_setting()
  {
    if (request()->isPost()) {
      $rule = [
        'ip_limit|来路IP限制'  => 'number',
        'minute_limit|每分钟内发送上限'  => 'number',
        'hour_limit|每小时内发送上限'  => 'number',
        'day_limit|每个自然日内发送上限'  => 'number',
      ];
      $data = [
        'ip_limit' => input('param.ip_limit', '', 'trim'),
        'server_ip' => input('param.server_ip/a', '', 'trim'),
        'minute_limit' => input('param.minute_limit', '', 'trim'),
        'hour_limit' => input('param.hour_limit', '', 'trim'),
        'day_limit' => input('param.day_limit', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['ip_limit'] = intval($data['ip_limit']);
      $data['minute_limit'] = intval($data['minute_limit']);
      $data['hour_limit'] = intval($data['hour_limit']);
      $data['day_limit'] = intval($data['day_limit']);
      $data['server_ip'] = (empty($data['server_ip'])) ? '' : implode(',', $data['server_ip']);
      $hasSetting = Db::connect('mongodb')->name('send_push_setting')->find();
      if (empty($hasSetting)) {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId();
        Db::connect('mongodb')->name('send_push_setting')->insert($data);
      } else {
        $this->redis->del('dever:push:setting:' . $this->uid, 'full');
        Db::connect('mongodb')->name('send_push_setting')->update($data);
      }
      return Result::Success('', '设置成功');
    } else {
      $infoData = Db::connect('mongodb')->name('send_push_setting')->find();
      $infoData['server_ip'] = (!empty($infoData['server_ip']))?explode(',', $infoData['server_ip']):[];
      return json(['code' => 200, 'data' => $infoData, 'msg' => '获取成功']);
    }
  }
  /**
   * 编辑服务器信息
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function edit_server_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'max:128',
        'type|推送类别'  => 'require',
        'status|配置状态'  => 'require',
        'server_secret|SecretKey'  => 'require',
        'silent|静默时间'  => 'number',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'platform' => input('param.platform', '', 'trim'),
        'type' => input('param.type', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'close_msg' => input('param.close_msg', '', 'trim'),
        'umeng_app_key' => input('param.umeng_app_key', '', 'trim'),
        'umeng_message_secret' => input('param.umeng_message_secret', '', 'trim'),
        'umeng_master_secret' => input('param.umeng_master_secret', '', 'trim'),
        'getui_app_id' => input('param.getui_app_id', '', 'trim'),
        'getui_app_key' => input('param.getui_app_key', '', 'trim'),
        'getui_app_secret' => input('param.getui_app_secret', '', 'trim'),
        'getui_master_secret' => input('param.getui_master_secret', '', 'trim'),
        'jiguang_app_key' => input('param.jiguang_app_key', '', 'trim'),
        'jiguang_master_secret' => input('param.jiguang_master_secret', '', 'trim'),
        'server_secret' => input('param.server_secret', '', 'trim'),
        'platform_alert_dingding_secret' => input('param.platform_alert_dingding_secret', '', 'trim'),
        'platform_alert_dingding_webhook_url' => input('param.platform_alert_dingding_webhook_url', '', 'trim'),
        'platform_alert_feishuqun_secret' => input('param.platform_alert_feishuqun_secret', '', 'trim'),
        'platform_alert_feishuqun_webhook_url' => input('param.platform_alert_feishuqun_webhook_url', '', 'trim'),
        'platform_alert' => input('param.platform_alert', '', 'trim'),
        'platform_alert_ss_id' => input('param.platform_alert_ss_id', '', 'trim'),
        'platform_alert_st_id' => input('param.platform_alert_st_id', '', 'trim'),
        'platform_alert_phone' => input('param.platform_alert_phone', '', 'trim'),
        'platform_alert_et_id' => input('param.platform_alert_et_id', '', 'trim'),
        'platform_alert_es_id' => input('param.platform_alert_es_id', '', 'trim'),
        'platform_alert_email' => input('param.platform_alert_email', '', 'trim'),
        'platform_alert_weixin_work_webhook_url' => input('param.platform_alert_weixin_work_webhook_url', '', 'trim'),
        'platform_alert_weixin_work_webhook_touser' => input('param.platform_alert_weixin_work_webhook_touser', '', 'trim'),
        'platform_alert_weixin_app_toparty' => input('param.platform_alert_weixin_app_toparty', '', 'trim'),
        'platform_alert_weixin_app_touser' => input('param.platform_alert_weixin_app_touser', '', 'trim'),
        'platform_alert_weixin_app_secret' => input('param.platform_alert_weixin_app_secret', '', 'trim'),
        'platform_alert_weixin_app_agentid' => input('param.platform_alert_weixin_app_agentid', '', 'trim'),
        'platform_alert_weixin_app_corpid' => input('param.platform_alert_weixin_app_corpid', '', 'trim'),
        'ww_apps_from' => input('param.ww_apps_from', '', 'trim'),
        'ww_id' => input('param.ww_id', '', 'trim'),
        'platform_alert_mp_weixin_template_openid' => input('param.platform_alert_mp_weixin_template_openid', '', 'trim'),
        'platform_alert_mp_weixin_template_mwid' => input('param.platform_alert_mp_weixin_template_mwid', '', 'trim'),
        'platform_alert_mp_weixin_template_template_id' => input('param.platform_alert_mp_weixin_template_template_id', '', 'trim'),
        'platform_goeasy_common_key' => input('param.platform_goeasy_common_key', '', 'trim'),
        'platform_goeasy_subscribe_key' => input('param.platform_goeasy_subscribe_key', '', 'trim'),
        'platform_goeasy_region' => input('param.platform_goeasy_region', '', 'trim'),
        'platform_goeasy_channel' => input('param.platform_goeasy_channel', '', 'trim'),
        'voice_url' => input('param.voice_url', '', 'trim'),
        'platform_api_url' => input('param.platform_api_url', '', 'trim'),
        'platform_api_url_password' => input('param.platform_api_url_password', '', 'trim'),
        'shielding_type' => input('param.shielding_type', '', 'trim'),
        'silent' => input('param.silent', 0, 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('push_server_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'push_num', '推送配置数量', $limitCount);
      $data['status'] = intval($data['status']);
      $data['silent'] = intval($data['silent']);
      $this->redis->del('dever:push:server:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $serverInfo = Db::connect('mongodb')->name('push_server_list')->field('hook_key')->where('_id', $data['id'])->find();
        if (empty($serverInfo)) {
          return Result::Error('配置不存在或已删除，编辑失败');
        }
        if (!isset($serverInfo['hook_key']) || empty($serverInfo['hook_key'])) {
          $data['hook_key'] = md5(createId($data['id']));
        }
        $status = Db::connect('mongodb')->name('push_server_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('PS');
        $data['hook_key'] = md5(createId($data['_id']));
        $status = Db::connect('mongodb')->name('push_server_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('push_server_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_hook_info()
  {
    if (request()->isPost()) {
      $rule = [
        'hook_platform|对接平台'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'hook_platform' => input('param.hook_platform', '', 'trim'),
        'yunxiao_token' => input('param.yunxiao_token', '', 'trim'),
        'gitee_token' => input('param.gitee_token', '', 'trim'),
        'git_token' => input('param.git_token', '', 'trim'),
        'dev_token' => input('param.dev_token', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $this->redis->del('dever:push:server:' . $data['id'], 'full');
      $serverInfo = Db::connect('mongodb')->name('push_server_list')->field('hook_key')->where('_id', $data['id'])->find();
      if (empty($serverInfo)) {
        return Result::Error('配置不存在或已删除，设置失败');
      }
      $this->redis->del('dever:push:server:' . $serverInfo['hook_key'], 'full');
      $status = Db::connect('mongodb')->name('push_server_list')->where('_id', $data['id'])->update($data);
      $tag = '设置';
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('push_server_list')->where('_id', $id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function reset_webhook_url()
  {
    $rule = [
      'id|必要信息'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $serverInfo = Db::connect('mongodb')->name('push_server_list')->where('_id', $data['id'])->find();
    if (empty($serverInfo)) {
      return Result::Error('配置不存在或已删除，重新获取失败');
    }
    $updateData['hook_key'] = md5(createId($data['id']));
    Db::connect('mongodb')->name('push_server_list')->where('_id', $data['id'])->update($updateData);
    return Result::Success('', '生成成功');
  }
  public function edit_tpl_cate_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'pid|上级分类'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'pid' => input('param.pid', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('push_tpl_cate')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('STC');
        $status = Db::connect('mongodb')->name('push_tpl_cate')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('push_tpl_cate')->where('_id', $id)->find();
      unset($data['uid']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_tpl_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'cate_id|模板分类'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'aliyun_tpl' => input('param.aliyun_tpl', '', 'trim'),
        'aliyun_tpl_code' => input('param.aliyun_tpl_code', '', 'trim'),
        'tencent_tpl' => input('param.tencent_tpl', '', 'trim'),
        'tencent_tpl_code' => input('param.tencent_tpl_code', '', 'trim'),
        'huawei_tpl_code' => input('param.huawei_tpl_code', '', 'trim'),
        'huawei_tpl' => input('param.huawei_tpl', '', 'trim'),
        'cate_id' => input('param.cate_id', '', 'trim'),
        'is_selected' => input('param.is_selected', '', 'trim'),
        'platform' => input('param.platform', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      $this->redis->del('dever:push:template:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('push_tpl_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('PT');
        $status = Db::connect('mongodb')->name('push_tpl_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('push_tpl_list')->where('_id', $id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function del_server()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('push_server_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_tpl()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('push_tpl_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_tpl_cate()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasTpl = Db::connect('mongodb')->name('push_tpl_list')->where('cate_id', $data['id'])->find();
    if (!empty($hasTpl)) {
      return Result::Error('该分类下存在推送模板，不允许删除');
    }
    $status = Db::connect('mongodb')->name('push_tpl_cate')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_push_log()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('send_push_log')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_log_all()
  {
    $rule = [
      'type|清空类型'  => 'require',
    ];
    $data = [
      'ps_id' => input('param.ps_id', '', 'trim'),
      'type' => input('param.type', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $where['uid'] = $this->uid;
    if (!empty($data['ps_id'])) {
      $where['ps_id'] = trim($data['ps_id']);
    }
    if ($data['type'] == 'all') {
      $status = Db::connect('mongodb')->name('send_push_log')->where($where)->delete();
    } else {
      $start_time = strtotime($data['send_time_ranges'][0]);
      $end_time = strtotime($data['send_time_ranges'][1]);
      if ($end_time - $start_time > 86400 * 90) {
        return Result::Error('时间跨度不能大于90天');
      }
      $status = Db::connect('mongodb')->name('send_push_log')->where($where)->whereBetweenTime('create_time', $start_time, $end_time)->delete();
    }
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_push_log_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('send_push_log')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_server_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('push_server_list')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function resend_push_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $list = Db::connect('mongodb')->name('send_push_log')->whereIn('_id', $data['id'])->select();
    foreach ($list as $key => $vo) {
      $logSms = json_decode($vo['params'], true);
      $logSms['psl_id'] = $vo['_id'];
      $logSms['platform'] = $vo['platform'];
      doSendPush($logSms,null,$this->uid);
    }
    return Result::Success('', '任务提交成功，请稍后通过【推送记录】查看发送结果');
  }
  public function send_push()
  {
    $rule = [
      'ps_id|推送配置'  => 'require',
      'title|推送标题'  => 'require',
      'type|消息类别'  => 'require',
    ];
    $data = [
      'ps_id' => input('param.ps_id', '', 'trim'),
      'title' => input('param.title', '', 'trim'),
      'type' => input('param.type', '', 'trim'),
      'cid' => input('param.cid', '', 'trim'),
      'click_type' => input('param.click_type', '', 'trim'),
      'click_type_content' => input('param.click_type_content', '', 'trim'),
      'channel_level' => input('param.channel_level', '', 'trim'),
      'msg_type' => input('param.msg_type', '', 'trim'),
      'atMobiles' => input('param.atMobiles', '', 'trim'),
      'params_json' => input('param.params_json', '', 'trim'),
      'msg_content' => input('param.msg_content', '', 'trim'),
      'content' => input('param.content', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $http = new \Yurun\Util\HttpRequest;
    doSendPush($data, $http,$this->uid);
    return Result::Success($data, '任务已提交，请稍后在日志中查看');
  }
  public function all_data()
  {
    $return['date'] = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) - 1);
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      '_id' => input('param._id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $whereTj[] = ['uid', '=', $this->uid];
    if (!empty($data['_id'])) {
      $whereTj[] = ['a_id', '=', $data['_id']];
    }
    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    if ($end_date == $start_date) {
      $cycle_type = 'hour';
      $cycle_num = 24;
    } else {
      $cycle_type = 'day';
      $cycle_num = ($end_date - $start_date) / 86400;
    }
    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $yestData = Db::connect('mongodb')->name('send_push_log_tj')->where($whereTj)->select();
    if (!empty($yestData)) {
      $yestData = $yestData->toArray();
    }
    $serialData = [];
    for ($i = 0; $i < $cycle_num; $i++) {
      if ($cycle_type == 'hour') {
        $nowTime = $start_date + $i * 3600;
        $serialData[date('H', $nowTime) . ':00'] = [];
      } else {
        $nowTime = $start_date + $i * 86400;
        $serialData[date('Ymd', $nowTime)] = [];
      }
    }
    if ($cycle_type == 'day') {
      $serialData[date('Ymd', $end_date)] = [];
    }
    foreach ($yestData as $key => $vo) {
      if ($cycle_type == 'hour') {
        $serialData[$vo['only_hour']][] = $vo;
      } else {
        $serialData[$vo['date']][] = $vo;
      }
    }
    $chartData = [];
    $return['total']['rv'] = 0;
    $return['total']['sv'] = 0;
    $num_type = '总数';
    if (!empty($data['_id'])) {
      $num_type = '数';
    }
    foreach ($serialData as $key => $vo) {
      // 日
      if (strlen($key) == 8) {
        if (!isset($vo['sv'])) {
          $vo['sv'] = 0;
        }
        if (!isset($vo['rv'])) {
          $vo['rv'] = 0;
        }
        foreach ($vo as $key2 => $vo2) {
          if (!empty($vo2)) {
            $vo['sv'] = $vo['sv'] + $vo2['sv'];
            $vo['rv'] = $vo['rv'] + $vo2['rv'];
            $return['total']['rv'] = $return['total']['rv'] + $vo2['rv'];
            $return['total']['sv'] = $return['total']['sv'] + $vo2['sv'];
          }
        }
        $year = substr($key, 0, 4);
        $month = substr($key, 4, 2);
        $day = substr($key, -2, 2);
        $charItem['date'] = $year . '-' . $month . '-' . $day;
        $charItem['value'] = $vo['sv'];
        $charItem['category'] = '推送发送' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = $vo['rv'];
        $charItem['category'] = '推送阅读' . $num_type;
        $chartData[] = $charItem;
      } else {
        // 时
        if (!isset($vo['sv'])) {
          $vo['sv'] = 0;
        }
        if (!isset($vo['rv'])) {
          $vo['rv'] = 0;
        }
        foreach ($vo as $key2 => $vo2) {
          if (!empty($vo2)) {
            $vo['rv'] = $vo['rv'] + $vo2['rv'];
            $vo['sv'] = $vo['sv'] + $vo2['sv'];
          }
        }
        $charItem['date'] = $key;
        $charItem['value'] = $vo['sv'];
        $charItem['category'] = '推送发送' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = $vo['rv'];
        $charItem['category'] = '推送阅读' . $num_type;
        $chartData[] = $charItem;
        $return['total']['sv'] = $return['total']['sv'] + $vo['sv'];
        $return['total']['rv'] = $return['total']['rv'] + $vo['rv'];
        $chartData[] = $charItem;
      }
    }
    $return['total']['rv_sv_rate'] = round($return['total']['rv'] / $return['total']['sv'] * 100, 2);
    $return['chart'] = $chartData;
    return Result::Success($return);
  }
  public function all_push_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'ps_id' => input('param.ps_id', '', 'trim'),
      'cid' => input('param.cid', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['ps_id'])) {
      $where['ps_id'] = $data['ps_id'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['ps_id'])) {
      $whereTj[] = ['ps_id', '=', $data['ps_id']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $fromType = '$cid';
    $hasAds = mongodb()->selectCollection('send_push_log_' . $this->uid)->aggregate([
      ['$match' => $where],
      ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
      ['$sort' => ['count' => -1]],
      ['$skip' => (int)$skip],
      ['$limit' => (int)$data['pageSize']],
    ]);
    $newData = [];
    foreach ($hasAds as $document) {
      $newData[] = (array)$document;
    }
    $totalNum = Db::connect('mongodb')->name('send_push_log')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function single_push_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'ps_id' => input('param.ps_id', '', 'trim'),
      'cid' => input('param.cid', '', 'trim'),
      'email_tab' => input('param.email_tab', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['ps_id'])) {
      $where['ps_id'] = $data['ps_id'];
    }
    if (!empty($data['cid'])) {
      $where['cid'] = $data['cid'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['cid'])) {
      $whereTj[] = ['cid', '=', $data['cid']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    switch ($data['email_tab']) {
      case '1':
        $fromType = '$ps_id';
        break;
      case '2':
        $fromType = '$title';
        if (!empty($data['ps_id'])) {
          $whereTj[] = ['ps_id', '=', $data['ps_id']];
        }
        break;
      case '3':
        $fromType = '$title';
        if (!empty($data['ps_id'])) {
          $whereTj[] = ['ps_id', '=', $data['ps_id']];
        }
        break;
      default:
        $fromType = '$cid';
        break;
    }
    if ($data['email_tab'] == '3') {
      $where['is_read'] = 1;
      $read_count = mongodb()->selectCollection('send_push_log_' . $this->uid)->count($where);
      $where['is_read'] = 0;
      $unread_count = mongodb()->selectCollection('send_push_log_' . $this->uid)->count($where);
      $newData = [];
      $itemBuild['_id'] = '已读量';
      $itemBuild['count'] = $read_count;
      $newData[] = $itemBuild;
      $itemBuild['_id'] = '未读量';
      $itemBuild['count'] = $unread_count;
      $newData[] = $itemBuild;
    } else {
      $hasAds = mongodb()->selectCollection('send_push_log_' . $this->uid)->aggregate([
        ['$match' => $where],
        ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
        ['$sort' => ['count' => -1]],
        ['$skip' => (int)$skip],
        ['$limit' => (int)$data['pageSize']],
      ]);
      $newData = [];
      foreach ($hasAds as $document) {
        $newData[] = (array)$document;
      }
    }

    $totalNum = Db::connect('mongodb')->name('send_push_log')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = ($totalNum == 0) ? 0 : round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public static function getPlatform($platform)
  {
    $platformText = '';
    if (is_array($platform)) {
      $platArr['phone'] = '短信';
      $platArr['email'] = '邮件';
      $platArr['weixin_work'] = '企业微信群机器人';
      $platArr['weixin_app'] = '企业微信应用消息';
      $platArr['dingding'] = '钉钉群机器人';
      $platArr['feishuqun'] = '飞书群机器人';
      $platArr['goeasy'] = 'GoEasy';
      $platArr['mp_weixin_template'] = '公众号模板消息';
      foreach ($platform as $vo) {
        if (isset($platArr[$vo])) {
          $platformText .= empty($platformText) ? $platArr[$vo] : ' / ' . $platArr[$vo];
        }
      }
    } else {
      switch ($platform) {
        case 'goeasy':
          $platformText = 'GoEasy';
          break;
        case 'phone':
          $platformText = '短信';
          break;
        case 'email':
          $platformText = '邮箱';
          break;
        case 'mp_weixin_template':
          $platformText = '公众号模板消息';
          break;
        case 'weixin_work':
          $platformText = '企业微信群机器人';
          break;
        case 'weixin_app':
          $platformText = '企业微信应用消息';
          break;
        case 'dingding':
          $platformText = '钉钉群机器人';
          break;
        case 'feishuqun':
          $platformText = '飞书群机器人';
          break;
        case 'aliyun':
          $platformText = '阿里推送';
          break;
        case 'tencent':
          $platformText = '腾讯推送';
          break;
        case 'getui':
          $platformText = '个推';
          break;
        case 'umeng':
          $platformText = '友盟';
          break;
        case 'jiguang':
          $platformText = '极光';
          break;
        default:
          $platformText = '未知';
          break;
      }
    }
    return empty($platformText) ? '未知' : $platformText;
  }
  public static function getType($type)
  {
    $platformText = '';
    switch ($type) {
      case 'app':
        $platformText = 'APP推送';
        break;
      case 'inbox':
        $platformText = '站内信';
        break;
      case 'alert':
        $platformText = '报警(业务)通知';
        break;
      default:
        $platformText = '未知';
        break;
    }
    return empty($platformText) ? '未知' : $platformText;
  }
}
